package com.dbs.donatebooksystem.controller;

import com.dbs.donatebooksystem.Service.AdminService;
import com.dbs.donatebooksystem.pojo.Admin;
import com.dbs.donatebooksystem.pojo.Result;
import com.dbs.donatebooksystem.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@CrossOrigin(origins = "http://localhost:8080", originPatterns = "http://localhost:8081")
@RequestMapping("/Admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @PostMapping("/Login")
    public Result Login(@RequestBody Admin admin){
        // 字段清洗（去除首尾空格）
        String account = admin.getAdmin() != null ? admin.getAdmin().trim() : "";
        String password = admin.getPassword() != null ? admin.getPassword().trim() : "";
        // 参数校验
        if (account.isEmpty() || password.isEmpty()) {
            return Result.error("用户名或密码不能为空");
        }
        // 调用服务层验证
        if (adminService.validateAdmin(account, password)) {
            log.info("管理员 {} 登录成功", account);
            Map<String, Object> claims = new HashMap<>();
            claims.put("admin",account);
            claims.put("password",password);
            String jwt = JwtUtils.generateJwt(claims);
            log.info(jwt);
            return Result.success(jwt);
        } else {
            log.warn("管理员登录失败：用户名={}，密码={}", account, password);
            return Result.error("用户名或密码错误");
        }
    }
}
